package customer.zspt.cn.customer.components.history;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import customer.zspt.cn.customer.Adapter.HistoryItemAdapter;
import customer.zspt.cn.customer.R;
import customer.zspt.cn.customer.bean.ChatMsgDao;
import customer.zspt.cn.customer.bean.GetChatMsgDao;
import customer.zspt.cn.customer.bean.GetGroupChatMsgDao;
import customer.zspt.cn.customer.bean.PersonalIDao;
import customer.zspt.cn.customer.bean.SkillListDao;
import customer.zspt.cn.customer.components.chat.FriendChat;
import customer.zspt.cn.customer.components.contact.contact_view;
import customer.zspt.cn.customer.components.group.group_view;
import customer.zspt.cn.customer.constant.chatMsgFieldName;
import customer.zspt.cn.customer.constant.constant;
import customer.zspt.cn.customer.sqlites.dao.chatMsgSqliteDao;
import customer.zspt.cn.customer.utils.ChatRecordSPUtils;
import customer.zspt.cn.customer.utils.MsgTipUtils;
import customer.zspt.cn.customer.utils.NetUtils;
import customer.zspt.cn.customer.utils.RequestPermissionsUtils;
import customer.zspt.cn.customer.utils.SPUtils;
import customer.zspt.cn.customer.utils.SqlOptionsUtils;
import customer.zspt.cn.customer.utils.TimestampToBj;
import customer.zspt.cn.customer.utils.WebScoket;
public class history extends Fragment implements View.OnClickListener {
    public HistoryItemAdapter adapter;
    private View emptyView;
    //历史记录的展示数据
    private List<Map<String, String>> historyLs = new ArrayList<>();
    private Gson gson = new Gson();
    private ListView chat_lv;

    //聊天对象
    private String chatObject;
    private List<String> chatContact = new ArrayList<>();
    private String token;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (adapter == null) {
                adapter = new HistoryItemAdapter(getActivity(), historyLs);
                chat_lv.setAdapter(adapter);
            } else {
                adapter.notifyDataSetChanged();
            }
            if (WebScoket.RFlistener != null) {
                WebScoket.RFlistener.OnRefactor();
            }
        }
    };
    //删除操作提示框
    private PopupWindow mPopupWindow;
    //无网络提示
    private TextView NotNetWorkTip;
    //获取数据库对象
    private chatMsgSqliteDao msgSqliteDao;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.history, null);
        msgSqliteDao = chatMsgSqliteDao.getInstance(getActivity());
        token = SPUtils.getString(getActivity(), "token", "");
        chat_lv = view.findViewById(R.id.chat_lv);
        emptyView = view.findViewById(R.id.empty_layout);
        NotNetWorkTip = view.findViewById(R.id.tip);
        chat_lv.setEmptyView(emptyView);
        RequestPermissionsUtils.checkRWritePermission(getActivity());
        setData();
        Listener();
        return view;
    }
    /*** 准备通讯录的数据*/
    private void setData() {
        int netWorkState = NetUtils.getNetWorkState(getContext());
        showNoNetWorkTip(netWorkState);
        Gson gson = new Gson();
        try {
            String ContaceData = SPUtils.getString(getContext(), constant.KEFU, "");
            if (!TextUtils.isEmpty(ContaceData)) {
                PersonalIDao personalI = gson.fromJson(ContaceData, PersonalIDao.class);
                setFriendData(personalI.data);
            }
            String skillList = SPUtils.getString(getContext(), constant.SKILL, "");
            //群聊
            if (!TextUtils.isEmpty(skillList)) {
                SkillListDao skillListDao = gson.fromJson(skillList, SkillListDao.class);
                setGroupData(skillListDao.data);
            }
        } catch (Exception e) {
            Toast.makeText(getContext(), "数据异常,可能是由于网络连接出现问题", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    //准备所有朋友的数据
    public void setFriendData(final List<PersonalIDao.userList> data) {
        if (data.size() == 0) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            PersonalIDao.userList userList = data.get(i);
            String UI = gson.toJson(userList);
            Log.w("UI", UI);
            SPUtils.setString(getContext(), constant.FRIEND_INFO + data.get(i).kefuId, UI);
        }
    }
    //准备群聊的数据
    public void setGroupData(final List<SkillListDao.SkillList> data) {
        if (data.size() == 0) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            SkillListDao.SkillList skillList = data.get(i);
            String SI = gson.toJson(skillList);
            SPUtils.setString(getContext(), constant.SKILLGROUP_INFO + data.get(i).skillId, SI);
        }
    }
    private void Listener() {
        WebScoket.GiveDataListener(new WebScoket.GetMsgListener() {
            @Override
            public void success(String data) {
                /**获取系统音量*/
                int current = MsgTipUtils.manager.getStreamVolume(AudioManager.STREAM_RING);
                if (current == 0) {
                    /**静音抖动*/
                    MsgTipUtils.vibrator.vibrate(new long[]{100, 300, 100, 300}, -1);
                } else {
                    MsgTipUtils.soundPool.play(MsgTipUtils.map.get(0), 1f, 1f, 0, 0, 1.2f);
                }
                addMsg(data);
            }
            @Override
            public void close() {
                //如果不是网络问题，则尝试重连
                if (NetUtils.getNetWorkState(getActivity()) != NetUtils.NOTNET) {
                    WebScoket.conn(token);
                }
            }
        });
        chat_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String userId = chatContact.get(position);
                pushAData(userId);
            }
        });
        chat_lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                chatObject = chatContact.get(position);
                showPopupWindow(view);
                return true;
            }
        });
    }
    private void pushAData(String id) {
        if(id==null)return;
        String[] split = id.split("_");
        Intent intent = new Intent(getContext(), FriendChat.class);
        /**聊天记录属于群聊*/
        if (id.contains("grouptype") && id.contains("group")) {
            String skillInfoDao = SPUtils.getString(getContext(), constant.SKILLGROUP_INFO + split[split.length - 1], "");
            Log.e("skillInfoDao", skillInfoDao);
            intent.putExtra("skillInfoDao", skillInfoDao);
            intent.putExtra("type", "1");
        }
        /**聊天记录属于客服*/
        else if (id.contains("usertype_kefu")) {
            String friendInfo = SPUtils.getString(getContext(), constant.FRIEND_INFO + split[split.length - 1], "");
            intent.putExtra("friendInfo", friendInfo);
            Log.e("friendInfo", friendInfo);
            intent.putExtra("type", "0");
        }
        /**聊天记录属于游客*/
        else if (id.contains("usertype_tourist")) {
            String touristInfo = SPUtils.getString(getContext(), constant.TOURIST + "/" + id, "");
            intent.putExtra("touristInfo", touristInfo);
            intent.putExtra("type", "2");
        }
        startActivity(intent);
    }

    private void LookAInfo(String id) {
        if(id==null)return;
        String[] split = id.split("_");
        Intent intent = null;
        /**聊天记录属于群聊*/
        if (id.contains("grouptype") && id.contains("group")) {
            intent = new Intent(getContext(), group_view.class);
            intent.putExtra("skillId", split[split.length-1]);
            startActivity(intent);
        }
        /**聊天记录属于客服*/
        else if (id.contains("usertype_kefu")) {
            intent = new Intent(getContext(), contact_view.class);
            intent.putExtra("kefuId", split[split.length-1]);
            startActivity(intent);
        }
    }
    //更新记录
    private Map<String, String> UpdataMSg(String userid) {
        Map<String, String> map = new HashMap<>();
        List<ChatMsgDao> query = msgSqliteDao.query(userid, 0, 1);
        if(query.size()==0||query==null) return null;
        ChatMsgDao dao = query.get(0);
        String avater = dao.getCHATOBJAVATER();
        String userName = dao.getCHATOBJNAME();
        long tempTime = dao.getTempTime();
        int type = dao.getMsgType();
        String chatContent = dao.getChatContent();
        chatContent = getShowContent(type,chatContent);
        //如果是群聊
        if(userid.contains("grouptype") && userid.contains("group")){
            avater = dao.getGROUPAVATAR();
            userName = dao.getGROUPNAME();
        }
        map.put("content",chatContent);
        map.put("timestamp",tempTime+"");
        map.put("userHearderIg",avater);
        map.put("userName",userName);
        String count = ChatRecordSPUtils.getRecordString(getContext(),userid,userid+"_count","0");
        map.put("UD_count",count);
        return map;
    }
    private String getShowContent(int type,String content) {
        switch (type) {
            case chatMsgFieldName.IMAGE:
                return "[图片]";
            case chatMsgFieldName.FILE:
                return "[文件]";
            case chatMsgFieldName.VIDEO:
                return "[音频]";
            case chatMsgFieldName.VOICE:
                return "[语音]";
            case chatMsgFieldName.ESSAY:
                return "[文章]";
            default:
                return content;
        }
    }
    private void addMsg(String data) {
        if(data.contains("usertype_tourist")){
            GetChatMsgDao dao = gson.fromJson(data, GetChatMsgDao.class);
            String tourist_info = gson.toJson(dao.data);
            SPUtils.setString(getContext(), constant.TOURIST + "/" + dao.data.fromid,tourist_info);
        }
        //群聊消息
        String history = ChatRecordSPUtils.getRecordString(getContext(), constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, "");
        GetGroupChatMsgDao getgroupChatMsgDao = gson.fromJson(data, GetGroupChatMsgDao.class);
        addMsgToSqlite(getgroupChatMsgDao);
        //添加聊天成员
        String replace = history.replace(getgroupChatMsgDao.data.id + ",", "");
        replace = getgroupChatMsgDao.data.id + ","+replace;
            ChatRecordSPUtils.setRecordString(getContext(), constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, replace);
        String count = ChatRecordSPUtils.getRecordString(getContext(), getgroupChatMsgDao.data.id, getgroupChatMsgDao.data.id + "_count", "0");
        int DRcount = Integer.parseInt(count) + 1;
        ChatRecordSPUtils.setRecordString(getContext(), getgroupChatMsgDao.data.id, getgroupChatMsgDao.data.id + "_count", DRcount + "");
        initHistory();
    }
    String avatar = "", content = "", fromid = "", userName = "",
            groupavatar="",groupname="",chatobjAvater="",chatobjName="";
    long timestamp = 0;
    int type = 0;
    private void addMsgToSqlite(GetGroupChatMsgDao getgroupChatMsgDao) {
        avatar = getgroupChatMsgDao.data.avatar!=null?getgroupChatMsgDao.data.avatar:"";
        content = getgroupChatMsgDao.data.content!=null?getgroupChatMsgDao.data.content:"";
        fromid = getgroupChatMsgDao.data.fromid!=null?getgroupChatMsgDao.data.fromid:getgroupChatMsgDao.data.id;
        groupavatar = getgroupChatMsgDao.data.groupavatar!=null?getgroupChatMsgDao.data.groupavatar:"";
        groupname = getgroupChatMsgDao.data.groupname!=null?getgroupChatMsgDao.data.groupname:"";
        timestamp = System.currentTimeMillis();
        userName = getgroupChatMsgDao.data.name!=null?getgroupChatMsgDao.data.name:"";
        //判断是不是群聊
        if(groupavatar.equals("")){
            chatobjAvater = avatar;
            chatobjName = userName;
        }else{
            chatobjAvater = getgroupChatMsgDao.data.groupavatar;
            chatobjName = getgroupChatMsgDao.data.groupname;
        }
        type = MsgType(content);
        String dateTime = TimestampToBj.getTime(timestamp);
        String sql = SqlOptionsUtils.SqlStr(fromid, avatar, content, chatMsgFieldName.FROM,
                timestamp, userName,
                chatMsgFieldName.UNREAD,
                type,groupavatar,groupname,chatobjAvater,chatobjName,dateTime);
        msgSqliteDao.addNewTable(fromid,sql);
    }
    //判断消息类型
    private int MsgType(String content) {
        String[] split = content.split("\\[");
        switch (split[0]) {
            case "img":
                return chatMsgFieldName.IMAGE;
            case "essay":
                return chatMsgFieldName.ESSAY;
            case "voice":
                return chatMsgFieldName.VOICE;
            case "video":
                return chatMsgFieldName.VIDEO;
            case "file":
                return chatMsgFieldName.FILE;
            default:
                return chatMsgFieldName.CONTENT;
        }
    }
    public void initHistory() {
        chatContact.removeAll(chatContact);
        if (historyLs != null) {
            historyLs.removeAll(historyLs);
        } else {
            historyLs = new ArrayList<>();
        }
        String data = ChatRecordSPUtils.getRecordString(getContext(),
                constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, "").trim();
        if (!data.equals("")){
            String[] split = data.split(",");
            for (int i = 0; i < split.length; i++) {
                if (TextUtils.isEmpty(split[i])) {
                    continue;}
                msgSqliteDao.addNewTable(split[i],"");
                chatContact.add(split[i]);
                Map<String, String> map = UpdataMSg(split[i]);
                if (map!=null) {
                    historyLs.add(map);
                }
            }
            mHandler.sendEmptyMessage(0);
        } else {
            mHandler.sendEmptyMessage(0);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        initHistory();
    }
    /*** 弹出一个窗体*/
    private void showPopupWindow(View view) {
        /*** 动画,透明动画，缩放动画*/
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        alpha.setDuration(200);
        //动画保持结束状态
        alpha.setFillAfter(true);
        //Animation.RELATIVE_TO_SELF依赖自身0.5f中间的位置
        ScaleAnimation scale = new ScaleAnimation(0, 1, 0, 1,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale.setDuration(200);
        scale.setFillAfter(true);
        //动画集合,动画速率是否一致
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(alpha);
        set.addAnimation(scale);
        View popupview = View.inflate(getContext(), R.layout.popupwindow_layout, null);
        TextView tv_delect = popupview.findViewById(R.id.tv_delect);
        TextView userInfo_Tv = popupview.findViewById(R.id.userInfo_Tv);
        if(chatObject.contains("usertype_tourist")&&chatObject!=null){
            userInfo_Tv.setVisibility(View.GONE);
        }
        else if(chatObject.contains("grouptype") && chatObject.contains("group")&&chatObject!=null){
            userInfo_Tv.setText("群资料");
        }
        tv_delect.setOnClickListener(this);
        userInfo_Tv.setOnClickListener(this);
        //创建popupwindow对象，挂载的对象，宽高，是否获取焦点
        mPopupWindow = new PopupWindow(popupview,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                true
        );
        //设置背景，回退生效
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        //设置窗体的位置
        mPopupWindow.showAsDropDown(view, 300, -view.getHeight()/3*2);
        //设置动画
        popupview.startAnimation(set);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_delect:
                showTipDialog(chatObject);
                break;
            case R.id.userInfo_Tv:
//                String count = ChatRecordSPUtils.getRecordString(getContext(), chatObject, chatObject + "_count", "0");
//                if (Integer.parseInt(count) == 0) {
//                    int DRcount = Integer.parseInt(count) + 1;
//                    ChatRecordSPUtils.setRecordString(getContext(), chatObject, chatObject + "_count", DRcount + "");
//                }
//                initHistory();
                LookAInfo(chatObject);
                break;
//            case R.id.tv_RI:
//                ChatRecordSPUtils.setRecordString(getContext(), chatObject, chatObject + "_count", "0");
//                initHistory();
 //               break;
        }
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
        }
    }
    private void showTipDialog(final String kefuId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提醒");
        builder.setMessage("清空不可恢复，是否继续！！！");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ChatRecordSPUtils.setRecordString(getContext(), kefuId, kefuId + "_count", "0");
                String history = ChatRecordSPUtils.getRecordString(getContext(),
                        constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, "");
                String replace = history.replace(kefuId + ",", "");
                ChatRecordSPUtils.setRecordString(getContext(), constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, replace);
                String sql = "DROP TABLE "+kefuId;
                msgSqliteDao.Update(sql);
                initHistory();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    public void showNoNetWorkTip(int netWorkState) {
        if(NotNetWorkTip!=null){
            if (netWorkState == NetUtils.NOTNET) {
                NotNetWorkTip.setVisibility(View.VISIBLE);
            } else {
                NotNetWorkTip.setVisibility(View.GONE);
            }
        }
    }
}
